package ces.lawsuit.controller;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Record;

import ces.lawsuit.model.BaseModel;
import ces.lawsuit.model.QueryModel;
import ces.lawsuit.model.Result;

public class BaseController<T extends BaseModel> extends Controller {
	private T t;
	private  static String SPACE=" ";
	protected Map<String,Object> returnMap=new HashMap();
	/**
	 * {
		"statusCode":"200",
		"message":"\u64cd\u4f5c\u6210\u529f",
		"tabid":"table, table-fixed",
		"closeCurrent":true,
		"forward":"",
		"forwardConfirm":""
	}**/
	@SuppressWarnings("unchecked")
	protected T getT() {
		try {
			Class cls = (Class) ((ParameterizedType) getClass().getGenericSuperclass())
					.getActualTypeArguments()[0];
			return (T) cls.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
public void renderSuccess(){
	
	 Result result=new Result();
	 returnMap.put("statusCode", "200");
	 returnMap.put("message", "操作成功");
	 returnMap.put("closeCurrent", "true");
	 
	 renderJson(JsonKit.toJson(returnMap));
}

public void renderFail(){
	 Result result=new Result();
	 result.setStatusCode("300");
	 result.setMessage("操作失败!");
	 result.setCloseCurrent(true);
	 renderJson(JsonKit.toJson(result));
	 
}
public Record getRecord(String modelName) {
    String modelNameAndDot = modelName + ".";
    Record model = new Record();
    boolean exist = false;
    Map<String, String[]> parasMap = getRequest().getParameterMap();
    for (Entry<String, String[]> e : parasMap.entrySet()) {
        String paraKey = e.getKey();
        if (paraKey.startsWith(modelNameAndDot)) {
            String paraName = paraKey.substring(modelNameAndDot.length());
            String[] paraValue = e.getValue();
            Object value = paraValue[0] != null ? (paraValue.length == 1 ? paraValue[0]
                    : array2str(paraValue, ","))
                    : null;
            model.set(paraName, value);
            exist = true;
        }
    }
    if (exist) {
        return model;
    } else {
        return null;
    }
}

private String array2str(String[] paraValue, String split) {
	StringBuffer sb=new StringBuffer();
	for(String str :paraValue){
		sb.append(str).append(split);
	}
	return sb.substring(sb.length(), sb.length()-1);
}
/**
 * 获取前端传来的数组对象并响应成Record列表
 * @author yongtree
 * @date 2013-9-26上午10:21:38
 * @param modelName
 * @return
 */
public List<Record> getRecords(String modelName) {
    List<String> nos = getModelsNoList(modelName);
    List<Record> list = new ArrayList<Record>();
    for (String no : nos) {
        Record r = getRecord(modelName + "[" + no + "]");
        if (r != null) {
            list.add(r);
        }
    }
    return list;
}

/**
 * 获取前端传来的数组对象并响应成Model列表
 * @author yuxb
 * @param modelClass
 * @param modelName
 * @return
 */
public List<T> getModels(Class<T> modelClass, String modelName) {
    List<String> nos = getModelsNoList(modelName);
    List<T> list = new ArrayList<T>();
    for (String no : nos) {
        T m = getModel(modelClass, modelName + "[" + no + "]");
        if (m != null) {
            list.add(m);
        }
    }
    return list;
}
public List getOtherModels(Class modelClass, String modelName) {
    List<String> nos = getModelsNoList(modelName);
    List list = new ArrayList<>();
    for (String no : nos) {
        Object m = getModel(modelClass, modelName + "[" + no + "]");
        if (m != null) {
            list.add(m);
        }
    }
    return list;
}
/**
 * 提取model对象数组的标号
 * 
 * @author yongtree
 * @date 2013-9-26上午10:17:14
 * @param modelName
 * @return
 */
private List<String> getModelsNoList(String modelName) {
    // 提取标号
    List<String> list = new ArrayList<String>();
    String modelNameAndLeft = modelName + "[";
    Map<String, String[]> parasMap = getRequest().getParameterMap();
    for (Entry<String, String[]> e : parasMap.entrySet()) {
        String paraKey = e.getKey();
        if (paraKey.startsWith(modelNameAndLeft)) {
            String no = paraKey.substring(paraKey.indexOf("[") + 1,
                    paraKey.indexOf("]"));
            if (!list.contains(no)) {
                list.add(no);
            }
        }
    }
    return list;
}
//获取查询条件
protected QueryModel getQueryModel(){
	
	StringBuffer sqlBf=new StringBuffer("1=1").append(SPACE);
	List<String> valueList=new ArrayList<String>();
	Map<String, String[]> parasMap = getRequest().getParameterMap();
	for(String key :parasMap.keySet()){
		System.out.println("key: "+key);
		if(key.endsWith(".operator")){
			String limit=parasMap.get(key)[0];
			String queryKey=key.substring(0,key.indexOf(".operator"));
		    sqlBf.append(" and (").append(queryKey).append(SPACE).append(limit).append(SPACE);
		    	sqlBf.append("?)");
		    String value=parasMap.get(queryKey)[0];
		    if("like".equalsIgnoreCase(limit)){
		    	value="%"+value+"%";
		    }
	        valueList.add(value);
		}
	}
	QueryModel qm=new QueryModel();
	qm.setQuerySql(sqlBf.toString());
	qm.setValueList(valueList);
	return qm;
}
}
